﻿/********
* Copyright © 深圳市新元素医疗技术开发有限公司 . All rights reserved.
* 
*  Description:
*  Create By Kain at 5/17/2011 4:23:46 PM
*  
*
*  Revision History:
*  Date                  Who                 What
*  
* 
********/

#region namespace

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cherry.Agile.Framework.Cache;
#endregion

namespace Cherry.Agile.Core
{
    /// <summary>
    /// 分布式同步锁
    /// </summary>
    public class DistributedLock:IDisposable
    {
        static Lazy<ICache> _cache = new Lazy<ICache>(GetCacheManager);
        string _key;
        static ICache GetCacheManager()
        {
            return CacheManager.GetCache("distributed");
        }
        /// <summary>
        /// 获取一个异步锁
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="timeout">超时时间</param>
        /// <returns></returns>
        public static DistributedLock Lock(string key, int timeout = 500)
        {
            var i = 0;
            bool isTimeOut = true;
            timeout = Math.Max(timeout, 100);
            while (i < timeout)
            {
                var val = _cache.Value.Get(key) as bool?;
                if (val == null || val == false)
                {
                    _cache.Value.Add(key,true);
                    isTimeOut = false;
                    System.Diagnostics.Trace.WriteLine("requried lock");
                    break;
                }
                System.Threading.Thread.Sleep(500);
                i += 500;
                System.Diagnostics.Trace.WriteLine("wait lock");
            }

            if (isTimeOut)
                throw new TimeoutException();

            return new DistributedLock() { _key = key };
            
        }

        /// <summary>
        /// 释放锁
        /// </summary>
        public void Dispose()
        {
            _cache.Value.Remove(_key);
        }
    }
}
